<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use app\user\model\UserModel;
use api\mall\model\UserLoginMonthModel;
use app\portal\model\UserPromoteRelationModel;
use app\portal\model\UserRealNameInfoModel;
use cmf\controller\BaseController;

use api\portal\service\UserInfoService;

/**
 * @OA\Tag(
 *     name="mall-login",
 *     description="账号相关"
 * )
 */
class LoginController extends BaseController
{

    /**
     * Swagger测试
     * @throws \think\exception\DbException
     * @OA\Get(
     *     tags={"mall-login"},
     *     path="/mall/login/test",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function test() {
        $this->success('test ok');
    }

    protected function getResponseType(): string
    {
        return 'json';
    }
    
    /**
     * 验证码密码注册
     * @OA\Post(
     *     tags={"mall-login"},
     *     path="/mall/login/register",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="username", type="string", example="18845456666"),
     *             @OA\Property(property="code", type="integer", example=123456),
     *             @OA\Property(property="password", type="string", example=""),
     *             @OA\Property(property="password_repeat", type="string", example=""),
     *             @OA\Property(property="parent_id", type="integer", example="0")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function register()
    {
        do {
            $data = $this->request->post();
            if (empty($data['username'])) {
                $result = '手机号码不能为空';
                break;
            }
            $username = $data['username'];
            if (!cmf_check_mobile($username)) {
                $result = '请输入正确的手机号码';
                break;
            }

            $userModel = new UserModel();
            $user = $userModel->where('mobile', $username)->find();
            $userInfoService = new UserInfoService();
            
            if (!empty($user)) {
                $result = '该手机号已注册，请直接登录！';
                break;
            }

            if (!isset($data['code']) || empty($data['code'])) {
                $result = '验证码不能为空';
                break;
            }
            if (cmf_check_verification_code($username, $data['code'], true) !== true) {
                // $result = 'result'.$result.$username.$code;
                break;
            }
            if ($data['code'] != "4444") {
                cmf_clear_verification_code($username);
            }

            // if (!isset($data['password']) || empty($data['password'])) {
            //     $result = '密码不能为空';
            //     break;
            // }

            // if (!isset($data['password_repeat']) || empty($data['password_repeat'])) {
            //     $result = '重复密码不能为空';
            //     break;
            // }

            // if ($data['password'] != $data['password_repeat']) {
            //     $result = '密码不一致，请重新输入！';
            //     break;
            // }

            $default_name = '用户';
            $avatar = '';
            $option = cmf_get_option('mall');
            // if(isset($option['default_male_avatar'])){
            //     $avatar = $option['default_male_avatar'];
            //     $default_name = empty($option['default_male_nick']) ? '用户' : $option['default_male_nick'];
            // }
            $user = [
                'user_type' => 2,
                'user_id' => cmf_random_number(12),
                'sex' => -1, //0,
                'create_time' => time(),
                'user_status' => 1,
                'avatar' => $avatar, // 'default_male_avatar'
                'user_nickname' => $default_name.(time()%100000),
                'last_login_ip' => $this->request->ip(),
                'mobile' => $username,
                'user_login' => $username,                        
                'pay_pass' => cmf_password('888888'),
                // 'user_pass' => cmf_password($data['password']),
                'user_activation_key' => $userInfoService->generateActivationCode()
            ];
            $user['id'] = $userModel->insertGetId($user);

            // 将parent_id和user_id的关系存入数据库cmf_user_promote_relation
            if (isset($data['parent_id']) && $data['parent_id'] > 0) {
                $userPromoteRelationModel = new UserPromoteRelationModel();
                $userPromoteRelationModel->insert([
                    'user_id' => $user['id'],
                    'parent_id' => $data['parent_id'],
                    'create_time' => time(),
                    'update_time' => time()
                ]);
            }

            $this->success('ok', url('/portal/Page/download'));
        } while (false);
        $this->error($result);
    }

    /**
     * 验证码/密码登录
     * @OA\Post(
     *     tags={"mall-login"},
     *     path="/mall/login/login",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="username", type="string", example="18845456666"),
     *             @OA\Property(property="code", type="integer", example=4444),
     *             @OA\Property(property="password", type="string", example="")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function login()
    {
        do {
            $data = $this->request->post();
            if (empty($data['username'])) {
                $result = '手机号码不能为空';
                break;
            }
            $username = $data['username'];
            if (!cmf_check_mobile($username)) {
                $result = '请输入正确的手机号码';
                break;
            }

            $userModel = new UserModel();
            $user = $userModel->where('mobile', $username)->find();
            $userInfoService = new UserInfoService();

            if (isset($data['code'])) {
                $code = $data['code'];
                $result = cmf_check_verification_code($username, $code, true);
                if ($result !== true) {                    
                    if (strpos($result, '过期') !== false) {
                        $result = "验证码已过期，请重新获取";
                    }
                    if (strpos($result, '验证码不正确') !== false) {
                        $result = "验证码不匹配，请重新输入";
                    }
                    break;
                }
                // 验证码登录新用户注册后性别和昵称密码默认值 客户端判断默认值显示修改页面
                if (empty($user)) {
                    $option = cmf_get_option('mall');
                    $default_name = '用户'.(time()%100000);
                    if(isset($option['default_male_nick'])){
                        $default_name = $option['default_male_nick'];
                    }
                    $avatar = '';
                    if(isset($option['default_male_avatar'])){
                        $avatar = $option['default_male_avatar'];
                    }
                    url('portal/user/set-password');
                    $user = [
                        'user_type' => 2,
                        'user_id' => cmf_random_number(12),
                        'sex' => -1, //0,
                        'create_time' => time(),
                        'user_status' => 1,
                        'avatar' => $avatar,
                        'user_nickname' => $default_name,
                        'last_login_ip' => $this->request->ip(),
                        'mobile' => $username,
                        'user_login' => $username,                        
                        'pay_pass' => '',
                        'user_activation_key' => $userInfoService->generateActivationCode()
                    ];
                    $userModel->insertGetId($user);
                    $user = $userModel->where('mobile', $username)->find();

                    // 新用户注册后，将parent_id和user_id的关系存入数据库cmf_user_promote_relation
                    $userPromoteRelationModel = new UserPromoteRelationModel();
                    $userPromoteRelationModel->insert([
                        'user_id' => $user['id'],
                        'parent_id' => 0,
                        'create_time' => time(),
                        'update_time' => time()
                    ]);
                }
                // 清理验证码
                if ($data['code'] != "4444") {
                    cmf_clear_verification_code($username);
                }
            } else if (isset($data['password'])) {
                if (false == $userInfoService->passwordValidate($data['password'])) {
                    $result = '密码格式错误，密码格式为8-16位，并且由大小写字母、数字、英文特殊符号两种以上组合';
                    break;
                }
                if (empty($user) || strlen($user['user_pass']) <= 0) {
                    $result = '该手机号暂未注册，请使用验证码注册并登录！';
                    break;
                }
                if (cmf_compare_password($data['password'], $user['user_pass']) !== true) {
                    $result = '密码错误！请重新输入...';
                    break;
                }
            } else {
                $result = '密码或验证码不能为空';
                break;
            }

            $user['needSetPassword'] = false;
            $user['needSetAvatar'] = false;
            $user['needSetRealName'] = false;
            if (empty($user['user_pass']) || strlen($user['user_pass']) <= 0) {
                $user['needSetPassword'] = true;
            }
            if ($user['sex'] < 0) {
                $user['needSetAvatar'] = true;
            }
            $userRealNameInfoModel = new UserRealNameInfoModel();
            if (empty($userRealNameInfoModel->where('user_id', $user['id'])->find())) {
                $user['needSetRealName'] = true;
            }

            unset($user['user_pass']);

            // 拉黑判断。
            if ($user['user_status'] == 0) {
                $result = '你已经限制登录，暂时无法登录';
                break;
            }
            if(empty($user['user_id'])){
                $user_id = cmf_random_number(12);
                $userModel->where('id',$user['id'])->update(
                        ['user_id'=>$user_id]
                );
            }
            $userInfoService->updateUserLoginLog($user);
            $userInfoService->updateUserFriendNum($user['id']);
        
            $token = cmf_generate_user_token($user['id'], 'web');
            $hookParam = [
                'user' => $user,
                'compare_password_result' => false,
            ];
            hook_one("user_login_start", $hookParam);
            $user['token'] = $token;

            $api = new \Tencent\TLSSigAPIv2(1600020287, '72bdae2f2efe09bdc5404710fdbe814d23a211dc775af6cbfafa2466f460a9d4');
            $sig = $api->genUserSig($user['id']);
            $user['im_sign'] = $sig;

            $user['avatar'] = cmf_get_image_url($user['avatar']);
            $user['pay_pass'] = (empty($user['pay_pass']) || strlen($user['pay_pass']) <= 0)?1:0;
            $this->success('ok', '', $user);
        } while (false);
        $this->error($result);
    }

    /**
     * 请求发送验证码
     * @OA\Post(
     *     tags={"mall-login"},
     *     path="/mall/login/sendCode",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="mobile", type="string", example="18845456666")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function sendCode()
    {
        $data = $this->request->post();
        do {
            if (empty($data['mobile']) || !cmf_check_mobile($data['mobile'])) {
                $result = '请输入正确的手机号码';
                break;
            }
            $code = cmf_get_verification_code($data['mobile']);
            if (false == $code) {
                $result = '验证码获取频繁，请稍后再试';
                break;
            }

            $smsModel = new \plugins\tencentcloud_sms\TencentcloudSmsPlugin();
            $sendResult = $smsModel->sendMobileVerificationCode(['mobile' => $data['mobile'], 'code' => $code]);
            if (false == $sendResult) {
                $result = '验证码发送失败，请稍后再试';
                break;
            }

            cmf_verification_code_log($data['mobile'], $code, time()+5*60);
            $this->success('验证码发送成功');
        } while (false);
        $this->error($result);
    }

    /**
     * 忘记密码
     * @OA\Post(
     *     tags={"mall-login"},
     *     path="/mall/login/resetPassword",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="mobile", type="string", example="18845456666"),
     *             @OA\Property(property="code", type="integer", example=4444),
     *             @OA\Property(property="user_pass", type="string", example=""),
     *             @OA\Property(property="user_pass_repeat", type="string", example="")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function resetPassword()
    {
        $data = $this->request->post();
        do {
            if (empty($data['mobile']) || !cmf_check_mobile($data['mobile'])) {
                $result = '请输入正确的手机号码';
                break;
            }
            $userModel = new UserModel();
            $user = $userModel->where('mobile', $data['mobile'])->find();
            if (empty($user)) {
                $result = '该手机号暂未注册，无法重置密码！';
                break;
            }
            if (empty($data['code'])) {
                $result = '验证码不能为空';
                break;
            }
            if (empty($data['user_pass'])) {
                $result = '密码不能为空';
                break;
            }
            if (empty($data['user_pass_repeat'])) {
                $result = '重复密码不能为空';
                break;
            }
            if ($data['user_pass'] != $data['user_pass_repeat']) {
                $result = '密码不一致，请重新输入！';
                break;
            }

            $userInfoService = new UserInfoService();
            if (false == $userInfoService->passwordValidate($data['user_pass'])) {
                $result = '密码格式错误，密码格式为8-16位，并且由大小写字母、数字、英文特殊符号两种以上组合';
                break;
            }

            $result = cmf_check_verification_code($data['mobile'], $data['code'], true);
            if ($result !== true) {
                if (strpos($result, '过期') !== false) {
                    $result = "验证码已过期，请重新获取";
                }
                if (strpos($result, '验证码不正确') !== false) {
                    $result = "验证码不匹配，请重新输入";
                }
                break;
            }

            //清理验证码
            if ($data['code'] != "4444") {
                cmf_clear_verification_code($data['mobile']);
            }

            $update = [];
            $update['user_pass'] = cmf_password($data['user_pass']);
            $userModel->where('id', $user['id'])->update($update);
            $this->success('ok');
        } while (false);
        $this->error($result);
    }
}
